package com.google.code.pathlet.eshop.config.web;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.code.pathlet.config.anno.ContainerIn;
import com.google.code.pathlet.config.anno.SpaceIn;
import com.google.code.pathlet.core.InstanceSpace;
import com.google.code.pathlet.core.Module;
import com.google.code.pathlet.core.PathletContainer;
import com.google.code.pathlet.web.PathletAjaxFilter;
import com.google.code.pathlet.web.PathletAjaxProcessor;
import com.google.code.pathlet.web.WebConfigManagerAccessor;
import com.google.code.pathlet.web.WebPathletConstants;
import com.google.code.pathlet.web.widget.ResponseLevel;
import com.google.code.pathlet.web.widget.ResponseMessage;

public class ModuleAction {
	
	private static Log log = LogFactory.getLog(ModuleAction.class);
	
	@ContainerIn
	private PathletContainer container;
	
	@SpaceIn(scope="request")
	private InstanceSpace requestSpace;
	
	private String moduleId;

	public String getModuleId() {
		return moduleId;
	}

	public void setModuleId(String moduleId) {
		this.moduleId = moduleId;
	}


	/**
	 * reload one specific module. The moduleId property will be use to indicated the reload module.
	 * @return
	 * @throws IOException
	 */
	public ResponseMessage reloadModule() throws IOException {

		PathletAjaxFilter.getModuleManager().reloadModule(moduleId);
		String message = "The module '" + moduleId + "' successfully reloaded!";
		return new ResponseMessage(ResponseLevel.INFO, message);
	}
	
	public Collection<Module> getModules() {
		
		return PathletAjaxFilter.getModuleManager().getModules();
	}
	
	/**
	 * Whole container will be reload, and the configuration of this container will be reloaded in this process.
	 * @return
	 * @throws IOException
	 */
	public ResponseMessage reloadContainer() throws IOException {
		log.info("Reloading the PathletContainer ...");
		HttpServletRequest request = (HttpServletRequest)requestSpace.getInstance(WebPathletConstants.REQUEST_PATH);
		
		container.destroy();
		
		//Reload the configuration and reset the ConfigManager of the PathletContainer
		WebConfigManagerAccessor configAccessor = WebConfigManagerAccessor.getInstance(request.getSession().getServletContext());
		container.setConfigManager(configAccessor.loadConfigManager());
		
		container.init();
		
		//After container.destroy() be invoked, the all InstanceSpace would be removed from container, includes InstanceSpace of this request. 
		//To make available InstanceSpace for this request, the new InstanceSpace should be created. 
		container.getSpace(WebPathletConstants.REQUEST_SCOPE, request, true);
		
		log.info("The PathetContainer successfully reloaded!");
		
		return new ResponseMessage(ResponseLevel.INFO, "Reload Success!");
	}

}